'use client'

import { useRef, useState, useEffect } from 'react'
import { 
  Box, 
  Flex, 
  HStack, 
  Text,
  useColorModeValue
} from '@chakra-ui/react'
import { QuillEditor, QuillEditorRef } from './QuillEditor'
import EditorToolbar from './EditorToolbar'
import { ChapterHeader } from './ChapterHeader'
import { QuillContent } from '@/types/chapter'
import { countWords, countChineseWords } from '@/utils/editor'
import { useEditor, EditorContent } from '@tiptap/react'
import StarterKit from '@tiptap/starter-kit'
import Placeholder from '@tiptap/extension-placeholder'
import Highlight from '@tiptap/extension-highlight'
import TextAlign from '@tiptap/extension-text-align'
import Image from '@tiptap/extension-image'
import Link from '@tiptap/extension-link'
import Table from '@tiptap/extension-table'
import TableCell from '@tiptap/extension-table-cell'
import TableHeader from '@tiptap/extension-table-header'
import TableRow from '@tiptap/extension-table-row'
import CodeBlockLowlight from '@tiptap/extension-code-block-lowlight'
import Underline from '@tiptap/extension-underline'
import TextStyle from '@tiptap/extension-text-style'
import { Color } from '@tiptap/extension-color'
import { FontFamily } from '@tiptap/extension-font-family'
import * as lowlight from 'lowlight'
import { useChapterStore } from '@/store/chapterStore'
import { useSettingsStore } from '@/store/settingsStore'
import EditorStatusBar from './EditorStatusBar'
import { useAutoSave } from '@/hooks/useAutoSave'

interface NovelEditorProps {
  chapterId?: string;
}

export const NovelEditor = ({ chapterId }: NovelEditorProps) => {
  const bgColor = useColorModeValue('white', 'gray.900')
  const toolbarBgColor = useColorModeValue('gray.50', 'gray.800')
  const borderColor = useColorModeValue('gray.200', 'gray.700')
  
  const { currentChapter, updateChapterContent } = useChapterStore()
  const { editorSettings } = useSettingsStore()
  
  // 添加字数统计状态
  const [wordCount, setWordCount] = useState(0)
  
  const editor = useEditor({
    extensions: [
      StarterKit,
      Placeholder.configure({
        placeholder: '开始创作您的小说...',
      }),
      Highlight,
      TextAlign.configure({
        types: ['heading', 'paragraph'],
        alignments: ['left', 'center', 'right', 'justify'],
      }),
      Image,
      Link.configure({
        openOnClick: false,
      }),
      Table.configure({
        resizable: true,
      }),
      TableRow,
      TableHeader,
      TableCell,
      CodeBlockLowlight.configure({
        lowlight,
      }),
      Underline,
      TextStyle,
      Color,
      FontFamily,
    ],
    content: currentChapter?.content || '',
    autofocus: true,
    onUpdate: ({ editor }) => {
      const html = editor.getHTML()
      if (currentChapter?.id) {
        updateChapterContent(currentChapter.id, html)
      }
    },
  })

  // 使用自动保存钩子
  useAutoSave(editor, currentChapter?.id)

  // 计算字数
  useEffect(() => {
    if (currentChapter?.content) {
      // 将HTML内容转换为纯文本后计算字数
      const tempElement = document.createElement('div')
      tempElement.innerHTML = currentChapter.content
      const text = tempElement.textContent || ''
      const count = countWords(text)
      setWordCount(count)
    } else {
      setWordCount(0)
    }
  }, [currentChapter?.content])
  
  if (!editor) {
    return null
  }

  return (
    <div className="novel-editor">
      <ChapterHeader
        title={currentChapter?.title || ''}
        subtitle={currentChapter?.subtitle || ''}
      />
      <EditorToolbar editor={editor} />
      <EditorContent editor={editor} />
      <EditorStatusBar editor={editor} />
    </div>
  )
} 